// ProjectName: go-learn-demo
// PackageName: elasticybxb
// Description: 低级API操作文档
// Author: hy.bai
// Date: 2025-09-01 星期一 18:34

package elasticybxb

import (
	"bytes"
	"fmt"
	"log/slog"
	"strings"

	"github.com/elastic/go-elasticsearch/v8/typedapi/types"
	"golang.org/x/net/context"
)

var AllDocument allDocument

type allDocument struct {
}

// 通过字符串添加文档
func (*allDocument) ElasticCreateDocByString() {
	client, _ := AllInitElastic.InitElasticByUsername()
	data := `{"name":"Go核心编程","author":"Neal Stephenson","release_date":"1992-06-01","page_count": 470}`

	// 全类API的方式创建文档
	resp, err := client.Index(ALL_DOC_NAME_STRING).Raw(strings.NewReader(data)).Do(context.TODO())
	if err != nil {
		slog.Error(fmt.Sprintf("Elastic Create Index Error: %s", err.Error()))
		return
	}
	// 打印结果
	fmt.Println(resp)
}

// 通过对象添加文档
func (*allDocument) ElasticCreateDocByStruct() {
	client, _ := AllInitElastic.InitElasticByUsername()
	book := &Book{
		Id:        1,
		Name:      "Go核心编程",
		Author:    "Neal Stephenson",
		TotalPage: 470,
	}

	// 全类API的方式创建文档
	resp, err := client.Index(ALL_DOC_NAME_STRUCT).Request(book).Do(context.TODO())
	if err != nil {
		slog.Error(fmt.Sprintf("Elastic Create Index Error: %s", err.Error()))
		return
	}
	// 打印结果
	fmt.Println(resp)
}

// 带Id的创建
func (*allDocument) ElasticCreateDocWithId() {
	client, _ := AllInitElastic.InitElasticByUsername()
	book := &Book{
		1,
		"go语言程序设计",
		"hy.bai",
		100,
	}
	// 带上自定义的ID
	resp, err := client.Index(ALL_DOC_NAME_WITH_ID).Id("1").Request(book).Do(context.TODO())
	if err != nil {
		slog.Error(fmt.Sprintf("Elastic Create Index Error: %s", err.Error()))
		return
	}
	// 打印结果
	fmt.Println(resp)
}

// 批量创建文档
func (*allDocument) ElasticCreateDocBatch() {
	client, _ := AllInitElastic.InitElasticByUsername()
	buffer := bytes.NewBufferString(`
		{"index":{"_id":"9780553351927"}}
		{"name":"Snow Crash","author":"Neal Stephenson","release_date":"2025-06-01","page_count": 470}
		{"index":{"_id":"9780441017225"}}
		{"name":"Revelation","author":"Alastair Reynol","release_date":"2000-03-15","page_count": 585}
	`)
	buffer.WriteString("\n")
	resp, _ := client.Bulk().Index(ALL_DOC_NAME_BATCH).Raw(buffer).Do(context.TODO())
	// 打印结果
	fmt.Println(resp)
}

// 通过查询条件删除
func (*allDocument) ElasticDeleteDocByCondition() {
	client, _ := AllInitElastic.InitElasticByUsername()
	query := types.NewQuery()
	query.Match = map[string]types.MatchQuery{
		"name": {Query: "Snow Crash"},
	}
	response, err := client.DeleteByQuery(ALL_DOC_NAME_BATCH).Query(query).Do(context.TODO())
	if err != nil {
		slog.Error("删除文档失败,原因是:", err.Error())
	}
	// 打印结果
	fmt.Println(response)
}

func TestAllElasticDoc() {
	AllDocument.ElasticDeleteDocByCondition()
}
